<template>
  <div>
    <el-form :model="passage" label-width="80px" size="small" :disabled="show">
      <el-form-item label="新闻标题">
        <el-input v-model="passage.title" class="inputStyle"></el-input>
      </el-form-item>

      <el-form-item label="发布时间">
        <el-date-picker
          v-model="passage.publishTime"
          type="date"
          format="YYYY年MM月dd 日"
          value-format="YYYY年MM月dd 日"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item label="新闻内容">
        <el-input
          v-model="passage.content"
          style="width: 700px"
          :autosize="{ minRows: 4, maxRows: 6 }"
          type="textarea"
          placeholder="请输入新闻内容"
        />
      </el-form-item>

      <el-form-item label="新闻类型" class="newsTypeClass">
        <el-select v-model="passage.passageTypeId" placeholder="请选择新闻类型">
          <el-option
            v-for="newsType in newsTypeList"
            :key="newsType.id"
            :label="newsType.type"
            :value="newsType.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="附件文件">
        <div v-for="file in fileList" :key="file.id" class="file-item">
          <img
            v-if="isImage(file.fileName)"
            :src="'/fileServer' + file.filePath"
            class="show-image"
            :alt="file.fileName"
          />
          <a v-else :href="'/fileServer' + file.filePath" target="_blank">
            {{ file.fileName }}
          </a>
        </div>
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" @click="update" disabled="show">更新</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import { QuillEditor } from "@vueup/vue-quill";

const OK = 200;
const router = useRouter();
const route = useRoute();

// 响应式数据
const passage = reactive({
  title: "",
  publishTime: "",
  content: "",
  passageTypeId: null,
});

const newsTypeList = ref([]);
const fileList = ref([]);
const show = ref(false);
// 编辑器配置
const editorOption = reactive({
  placeholder: "输入新闻内容：",
  theme: "snow",
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ header: 1 }, { header: 2 }],
      [{ list: "ordered" }, { list: "bullet" }],
      [{ script: "sub" }, { script: "super" }],
      [{ indent: "-1" }, { indent: "+1" }],
      [{ direction: "rtl" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ["clean"],
      ["link", "image"],
    ],
  },
});

// 文件类型检测
const isImage = (fileName) => {
  const ext = fileName?.split(".").pop()?.toLowerCase();
  return ["png", "jpg", "jpeg", "gif"].includes(ext);
};

// 获取新闻数据
const fetchPassage = async (id) => {
  try {
    const { data } = await axios.get(`/api/passages/${id}`);
    if (data.code === OK) {
      Object.assign(passage, data.data);
      fileList.value = data.data.fileList || [];
    }
  } catch (error) {
    ElMessage.error("获取新闻详情失败");
  }
};

// 获取新闻类型列表
const fetchNewsTypes = async () => {
  try {
    const { data } = await axios.get("/api/passageTypes");
    if (data.code === OK) {
      newsTypeList.value = data.data;
    }
  } catch (error) {
    ElMessage.error("获取新闻类型失败");
  }
};

// 更新新闻
const update = async () => {
  try {
    const { data } = await axios.put("/api/passages", passage);
    if (data.code === OK) {
      ElMessage.success("更新成功");
      setTimeout(() => router.push({ name: "PassageList" }), 1500);
    } else {
      ElMessage.error(data.message);
    }
  } catch (error) {
    ElMessage.error("更新请求失败");
  }
};

// 返回上一页
const goBack = () => router.go(-1);

// 生命周期钩子
onMounted(() => {
  const id = route.query.id || route.params.id;
  show.value = !Boolean(route.query.show);
  if (id) fetchPassage(id);
  fetchNewsTypes();
});

// 路由参数监听
watch(
  () => route.params.id,
  (newId) => {
    if (newId) fetchPassage(newId);
  }
);
</script>

<style scoped>
.show-image {
  width: 350px;
  height: 220px;
  object-fit: cover;
  margin: 8px 0;
}

.editor {
  height: 300px;
  margin-bottom: 40px;
}

.newsTypeClass {
  margin: 20px 0;
}

.file-item {
  margin: 8px 0;
}
</style>
